//
//  MainViewController.m
//  DYS
//
//  Created by 房 国生 on 15/6/17.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "MainViewController.h"
#import "SpotViewController.h"
#import "WebViewController.h"
#import "EScrollerView.h"
#import "CommonService.h"
#import "MapBaiduViewController.h"
#import "SpotDetailViewController.h"
#import "AroundViewController.h"

#import "FindViewController.h"
#import "MoreViewController.h"
#import "MeViewController.h"
#import "LocalProductViewController.h"
#import "IntroduceViewController.h"
#import "TicketProductViewController.h"
#import "MapImageViewController.h"
#import "NativeProductTableViewController.h"
#import "AroundTableViewController.h"
#import "FindRecomViewController.h"
#import "EECircularMusicPlayerControl.h"
#import "ParkComment2ViewController.h"
#import "RecFoundViewController.h"
#import "LoginViewController.h"
#import "MessageDetailViewController.h"

#import "ZipArchive.h"
#import "RoadLineEntity.h"

#import "DownLoadOperation.h"
#import "UIImageView+LK.h"
#import "UIButton+WebCache.h"
#import "ScanBarCodeViewController.h"
#import "JT3DScrollView.h"
#import "DBManager.h"
#import "AppDelegate.h"
#import "DXAlertView.h"
#import "OpenUDID.h"
#import "XGPush.h"

#import "TCBlobDownloadManager.h"



@interface MainViewController ()<EScrollerViewDelegate, ScanBarCodeDelegate, UIScrollViewDelegate, TCBlobDownloadDelegate>
@property (nonatomic , unsafe_unretained) TCBlobDownloadManager *sharedDownloadManager;

@property (nonatomic, strong) DownLoadOperation* operation;

@property (nonatomic, strong) IBOutlet UIScrollView *scrollViewMain;
@property (nonatomic, strong) FindRecomViewController *findRecomVC;
@property (nonatomic, strong) FindViewController *findVC;
@property (nonatomic, strong) MoreViewController *moreVC;
@property (nonatomic, strong) MeViewController *meVC;

@property (nonatomic, strong) IBOutlet UIButton *btnHome;
@property (nonatomic, strong) IBOutlet UIButton *btnFind;
@property (nonatomic, strong) IBOutlet UIButton *btnMe;
@property (nonatomic, strong) IBOutlet UIButton *btnMore;
@property (nonatomic, strong) IBOutlet UILabel *labelHome;
@property (nonatomic, strong) IBOutlet UILabel *labelFind;
@property (nonatomic, strong) IBOutlet UILabel *labelMe;
@property (nonatomic, strong) IBOutlet UILabel *labelMore;

@property (nonatomic, strong) IBOutlet UIButton *btnScan;
@property (nonatomic, strong) IBOutlet UIButton *btnPhone;
@property (nonatomic, strong) IBOutlet UILabel *labelTitle;

@property (nonatomic, strong) IBOutlet UISegmentedControl *segmentedControl;

@property (nonatomic, strong) IBOutlet EECircularMusicPlayerControl *btnMap;
@property (nonatomic, strong) IBOutlet EECircularMusicPlayerControl *btnSpot;
@property (nonatomic, strong) IBOutlet EECircularMusicPlayerControl *btnGuid;

@property (nonatomic, strong) IBOutlet UIProgressView *progressView;
@property (nonatomic, strong) IBOutlet UILabel *labelProgress;

@property (assign) int mPage;
@property (assign) BOOL downloading;

@property (nonatomic, strong) NSMutableArray *mutableArrayActivity;
@property (weak, nonatomic) IBOutlet JT3DScrollView *scrollViewActvity;

@property (assign) int type;

@property (nonatomic, strong) NSMutableArray *arraySpot;
@property (nonatomic, strong) NSMutableArray *arrayBusiness;
@property (nonatomic, strong) NSMutableArray *arrayToilet;
@property (nonatomic, strong) NSMutableArray *arrayRoadLine;

@property (nonatomic, strong) NSDictionary *dicPushMessage;

@end

@implementation MainViewController
@synthesize scrollViewMain, findVC, moreVC, meVC, findRecomVC;
@synthesize btnFind, btnHome, btnMe, btnMore, labelFind, labelHome, labelMe, labelMore;
@synthesize segmentedControl, labelTitle, scrollViewActvity;
@synthesize mPage, btnPhone, btnScan, mutableArrayActivity;
@synthesize arrayBusiness, arraySpot, arrayToilet, arrayRoadLine;
@synthesize parkEntity, progressView, dicPushMessage;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    [self.navigationController setNavigationBarHidden:YES];
    [AppDelegate instance].dicCurrentCity = [[NSDictionary alloc]initWithObjectsAndKeys:@"北京", @"cname",@"1", @"id", nil];
    
    [self initAdController];
    
    arraySpot = [[NSMutableArray alloc] init];
    arrayBusiness = [[NSMutableArray alloc] init];
    arrayToilet = [[NSMutableArray alloc] init];
    arrayRoadLine = [[NSMutableArray alloc] init];
    mutableArrayActivity = [[NSMutableArray alloc] init];
    
//    findRecomVC = [[FindRecomViewController alloc] init];
//    findVC = [[FindViewController alloc] init];
//    moreVC = [[MoreViewController alloc] init];
//    meVC = [[MeViewController alloc] init];
//    
//    findRecomVC.view.frame = CGRectMake(0, 64, self.scrollViewMain.frame.size.width, 453);
//    findVC.view.frame = CGRectMake(0, 64, self.scrollViewMain.frame.size.width, 453);
//    moreVC.view.frame = CGRectMake(0, 64, self.scrollViewMain.frame.size.width, 453);
//    meVC.view.frame = CGRectMake(-1, 64, self.scrollViewMain.frame.size.width, 453);
//    
//    findRecomVC.mainVC = self;
//    findVC.mainVC = self;
//    findVC.parkId = @"274";
//    moreVC.mainVC = self;
//    meVC.mainVC = self;
//    
//    [self.view addSubview:findRecomVC.view];
//    [self.view addSubview:findVC.view];
//    [self.view addSubview:moreVC.view];
//    [self.view addSubview:meVC.view];
//    
//    [self showMainView:0];
    
    self.scrollViewActvity.effect = JT3DScrollViewEffectNone;
    self.scrollViewActvity.delegate = self; // Use only for animate nextButton and previousButton
    self.scrollViewActvity.pagingEnabled = NO;
    
    //[self getSpotFromInternetData];
    [self getParkData];
    [self getActivityData];
    
    progressView.hidden = YES;
    _labelProgress.hidden = YES;
    _downloading = NO;
    
    self.sharedDownloadManager = [TCBlobDownloadManager sharedDownloadManager];
    
    [XGPush setTag:@"tag"];
    //[super getAPPVersion:NO AppId:@"4"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (IBAction)doMapAction:(id)sender {
    
    if (_downloading == YES) {
        ALERT_ERR_MSG(SourceDownloading);
    } else {
        if ([self loadSpotData] == YES) {
            
            NSMutableArray *array = [[NSMutableArray alloc] init];
            
            for (int i = 0; i < [arraySpot count]; i++) {
                SpotEntity *entity = [arraySpot objectAtIndex:i];
                [array addObject:entity];
            }
            for (int i = 0; i < [arrayBusiness count]; i++) {
                SpotEntity *entity = [arrayBusiness objectAtIndex:i];
                [array addObject:entity];
            }
            for (int i = 0; i < [arrayToilet count]; i++) {
                SpotEntity *entity = [arrayToilet objectAtIndex:i];
                [array addObject:entity];
            }
            
            if ([parkEntity.use_baidumap isEqualToString:@"0"] == YES) {
                MapImageViewController *vc = [[MapImageViewController alloc] init];
                vc.parkEntity = parkEntity;
                vc.mutableArray = array;
                vc.mutableArrayRoad = arrayRoadLine;
                [self.navigationController pushViewController:vc animated:YES];
            } else {
                MapBaiduViewController *vc = [[MapBaiduViewController alloc] init];
                vc.parkEntity = parkEntity;
                vc.mutableArray = array;
                vc.mutableArrayRoad = arrayRoadLine;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    }
}

- (IBAction)doIntroduceAction:(id)sender {
    IntroduceViewController *vc = [[IntroduceViewController alloc] init];
    vc.parkId = [NSString stringWithFormat:@"%@",parkEntity.ID];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)doGuideAction:(id)sender {
    
    if (_downloading == YES) {
        ALERT_ERR_MSG(SourceDownloading);
    } else {
        if ([self loadSpotData] == YES) {
            SpotEntity *entity = [arraySpot objectAtIndex:0];
            SpotDetailViewController *vc = [[SpotDetailViewController alloc] init];
            vc.entity = entity;
            vc.parkEntity = parkEntity;
            vc.musicArrayNumber = 0;
            vc.musicArray = arraySpot;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (IBAction)doSpotAction:(id)sender {
    if (_downloading == YES) {
        ALERT_ERR_MSG(SourceDownloading);
    } else {
        if ([self loadSpotData] == YES) {
            SpotViewController *vc = [[SpotViewController alloc] init];
            vc.parkEntity = parkEntity;
            vc.mutableArraySpot = arraySpot;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (IBAction)doTicketAction:(id)sender {
    //    TicketProductViewController *vc = [[TicketProductViewController alloc] init];
    //    [self.navigationController pushViewController:vc animated:YES];
    WebViewController *vc = [[WebViewController alloc] init];
    vc.url = @"http://www.ly.com/scenery/BookSceneryTicket_3280.html#refid=94620980";
    vc.vcTitle = @"门票";
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)doAroundAction:(id)sender {
    AroundViewController *vc = [[AroundViewController alloc]init];
    vc.parkEntity = parkEntity;
    vc.category = 1;
    vc.enter_type = 1;
    //AroundTableViewController *vc = [[AroundTableViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    //[vc loadArroundData:1];
}

- (IBAction)doFoodAction:(id)sender {
    AroundViewController *vc = [[AroundViewController alloc]init];
    vc.parkEntity = parkEntity;
    vc.category = 2;
    //AroundTableViewController *vc = [[AroundTableViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    //[vc loadArroundData:2];
}

- (IBAction)doHappyAction:(id)sender {
    AroundViewController *vc = [[AroundViewController alloc]init];
    vc.parkEntity = parkEntity;
    vc.category = 3;
    //AroundTableViewController *vc = [[AroundTableViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    //[vc loadArroundData:3];
}

- (IBAction)doLPAction:(id)sender {
    LocalProductViewController *vc = [[LocalProductViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)doWeiXinAction:(id)sender {
    MapImageViewController *vc = [[MapImageViewController alloc] init];
    vc.parkEntity = parkEntity;
    vc.mutableArrayRoad = arrayRoadLine;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)scanAction:(id)sender {
    ScanBarCodeViewController * vc = [[ScanBarCodeViewController alloc]init];
    vc.delegate = self;
    [self presentViewController:vc animated:YES completion:^{
        
    }];
}

- (IBAction)callPhone:(id)sender {

    if (mPage == 0) {
        NSString *number = parkEntity.phone;// 此处读入电话号码
        // NSString *num = [[NSString alloc] initWithFormat:@"tel://%@",number]; //number为号码字符串 如果使用这个方法 结束电话之后会进入联系人列表
        NSString *num = [[NSString alloc] initWithFormat:@"telprompt://%@",number]; //而这个方法则打电话前先弹框  是否打电话 然后打完电话之后回到程序中 网上说这个方法可能不合法 无法通过审核
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]]; //拨号
    } else if (mPage == 1) {
        UserEntity *entity = [UserEntity sharedInstance];
        if (entity.userId == nil) {
            LoginViewController *vc = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            RecFoundViewController *vc = [[RecFoundViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (void) initNavigateionBar {
    
    btnScan =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    [btnScan setBackgroundImage:[UIImage imageNamed:@"离线下载-白@2x"] forState:UIControlStateNormal];
    [btnScan addTarget:self action:@selector(scanAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *nextButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnScan];
    self.navigationItem.rightBarButtonItem = nextButtonItem;
}

- (void) initAdController {
    
    //NSDictionary *dicCurrentCity = [[NSDictionary alloc]initWithObjectsAndKeys:@"北京", @"cname",@"1", @"id", nil];
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           self.parkId, @"parkid",
                           @"advert_top", @"keyword", nil];
    
    [service getNetWorkData:param
                       Path:ADPATH
                  Successed:^(id entity) {
                      NSDictionary *row = (NSDictionary *)entity;
                      
                      NSMutableArray *array = [row objectForKey:@"rows"];
                      NSMutableArray *arrayAD = [[NSMutableArray alloc] init];
                      
                      EScrollerView *scroller = nil;
                      for (NSDictionary* attributes in array) {
                          HomeAdvertEntity *entity = [[HomeAdvertEntity alloc] init];
                          entity = [entity initWithAttributes:attributes];
                          [arrayAD addObject:entity];
                      }
                      
                      if ([array count] == 0) {
                          //                          NSMutableArray *array2 = [[NSMutableArray alloc] init];
                          //                          [array2 addObject:arrayAD];
                          //                          scroller = [[EScrollerView alloc] initWithFrameRect:CGRectMake(0, 0, 320, 140)
                          //                                                                   ImageArray:array2
                          //                                                                   TitleArray:nil];
                      } else {
                          scroller = [[EScrollerView alloc] initWithFrameRect:CGRectMake(0, 0, 320, 160)
                                                                   ImageArray:arrayAD
                                                                   TitleArray:nil];
                      }
                      
                      scroller.delegate=self;
                      [self.scrollViewMain addSubview:scroller];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
}

- (void) getParkData {
    
    [super showLoadingView:YES];
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           self.parkId, @"id",
                           @"8ae86cfacd9744b68aecd3a6caa5f78f", @"appid", nil];
    
    [service getNetWorkData:param
                       Path:PARK_ENTITY_PATH
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      NSDictionary *dic_row = [dic objectForKey:@"row"];
                      
                      parkEntity = [[ParkEntity alloc] init];
                      parkEntity = [parkEntity initWithAttributes:dic_row];
                      
                      [super showLoadingView:NO];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [super showLoadingView:NO];
                      DebugLog(@"%@", message);
                  }];
}

- (void) pushScanResultInfo:(NSString *)url {
    
    WebViewController *vc =[[WebViewController alloc] init];
    vc.vcTitle = @"扫描";
    vc.url = url;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void) finishDownload:(BOOL)success {
    DebugLog(@"donwnload finish status = %d", success);
}

- (void)performBlock:(void(^)())block afterDelay:(NSTimeInterval)delay {
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), block);
}

- (void) saveDataToFile:(NSString *)url SavePath:(NSString *)aSavePath FileName:(NSString *)aFileName{
    
}

- (void) getSpotFromInternetData {
    //读取本地数据库是否有该文件
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           self.parkId, @"parkid", nil];
    
    [service getNetWorkData:param
                       Path:SPOTPATH
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"attractionRows"];
                      
                      for (NSDictionary* attributes in array) {
                          SpotEntity *entity2 = [[SpotEntity alloc] init];
                          entity2 = [entity2 initWithAttributes:attributes];
                          [arraySpot addObject:entity2];
                      }
                      
                      array = [dic objectForKey:@"businessRows"];
                      
                      for (NSDictionary* attributes in array) {
                          SpotEntity *entity2 = [[SpotEntity alloc] init];
                          entity2 = [entity2 initWithAttributes:attributes];
                          [arrayBusiness addObject:entity2];
                      }
                      
                      array = [dic objectForKey:@"toiletRows"];
                      
                      for (NSDictionary* attributes in array) {
                          SpotEntity *entity2 = [[SpotEntity alloc] init];
                          entity2 = [entity2 initWithAttributes:attributes];
                          [arrayToilet addObject:entity2];
                      }
                      
                      array = [dic objectForKey:@"roadline"];
                      for (NSDictionary* attributes in array) {
                          RoadLineEntity *entity2 = [[RoadLineEntity alloc] init];
                          entity2 = [entity2 initWithAttributes:attributes];
                          [arrayRoadLine addObject:entity2];
                      }
                  } Failed:^(NSInteger errorCode, NSString *message) {
                  }];
}
//
//- (IBAction)doShowHomeVC:(id)sender {
//    [self showMainView:0];
//}
//
//- (IBAction)doShowFindVC:(id)sender {
//    [self showMainView:1];
//}
//
//- (IBAction)doShowMeVC:(id)sender {
//    [self showMainView:2];
//}
//
//- (IBAction)doShowMoreVC:(id)sender {
//    [self showMainView:3];
//}
//
//- (void) showMainView:(int) page {
//    mPage = page;
//    btnScan.hidden = NO;
//    btnPhone.hidden = NO;
//    segmentedControl.hidden = YES;
//    labelTitle.hidden = NO;
//    [btnPhone setBackgroundImage:[UIImage imageNamed:@"call_icon.png"] forState:UIControlStateNormal];
//    
//    if (page == 0) {
//        self.scrollViewMain.hidden = NO;
//        findRecomVC.view.hidden = YES;
//        findVC.view.hidden = YES;
//        meVC.view.hidden = YES;
//        moreVC.view.hidden = YES;
//        self.labelTitle.text = @"青龙峡";
//        
//        [btnHome setBackgroundImage:[UIImage imageNamed:@"首页_01"] forState:UIControlStateNormal];
//        [btnFind setBackgroundImage:[UIImage imageNamed:@"发现_02"] forState:UIControlStateNormal];
//        [btnMe setBackgroundImage:[UIImage imageNamed:@"我_02"] forState:UIControlStateNormal];
//        [btnMore setBackgroundImage:[UIImage imageNamed:@"更多_02"] forState:UIControlStateNormal];
//        
//        labelHome.textColor = [UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1];
//        labelFind.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        labelMe.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        labelMore.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        
//    } else if (page == 1) {
//        self.scrollViewMain.hidden = YES;
//        findVC.view.hidden = NO;
//        findRecomVC.view.hidden = YES;
//        meVC.view.hidden = YES;
//        segmentedControl.hidden = NO;
//        btnScan.hidden = YES;
//        labelTitle.hidden = YES;
//        moreVC.view.hidden = YES;
//        
//        [btnHome setBackgroundImage:[UIImage imageNamed:@"首页_02"] forState:UIControlStateNormal];
//        [btnFind setBackgroundImage:[UIImage imageNamed:@"发现_01"] forState:UIControlStateNormal];
//        [btnMe setBackgroundImage:[UIImage imageNamed:@"我_02"] forState:UIControlStateNormal];
//        [btnMore setBackgroundImage:[UIImage imageNamed:@"更多_02"] forState:UIControlStateNormal];
//        
//        labelHome.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        labelFind.textColor = [UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1];
//        labelMe.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        labelMore.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        
//        btnScan.hidden = YES;
//        labelTitle.hidden = YES;
//        [btnPhone setBackgroundImage:[UIImage imageNamed:@"发现_01-白@2x"] forState:UIControlStateNormal];
//        
//    } else if (page == 2) {
//        self.scrollViewMain.hidden = YES;
//        findVC.view.hidden = YES;
//        meVC.view.hidden = NO;
//        moreVC.view.hidden = YES;
//        btnPhone.hidden = YES;
//        btnScan.hidden = YES;
//        labelTitle.hidden = NO;
//        labelTitle.text = @"我的";
//        
//        segmentedControl.selectedSegmentIndex = 0;
//        [btnHome setBackgroundImage:[UIImage imageNamed:@"首页_02"] forState:UIControlStateNormal];
//        [btnFind setBackgroundImage:[UIImage imageNamed:@"发现_02"] forState:UIControlStateNormal];
//        [btnMe setBackgroundImage:[UIImage imageNamed:@"我_01"] forState:UIControlStateNormal];
//        [btnMore setBackgroundImage:[UIImage imageNamed:@"更多_02"] forState:UIControlStateNormal];
//        
//        labelHome.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        labelFind.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        labelMe.textColor = [UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1];
//        labelMore.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        
//    } else if (page == 3) {
//        self.scrollViewMain.hidden = YES;
//        findVC.view.hidden = YES;
//        meVC.view.hidden = YES;
//        moreVC.view.hidden = NO;
//        
//        btnPhone.hidden = YES;
//        btnScan.hidden = YES;
//        labelTitle.hidden = NO;
//        labelTitle.text = @"更多";
//        
//        [btnHome setBackgroundImage:[UIImage imageNamed:@"首页_02"] forState:UIControlStateNormal];
//        [btnFind setBackgroundImage:[UIImage imageNamed:@"发现_02"] forState:UIControlStateNormal];
//        [btnMe setBackgroundImage:[UIImage imageNamed:@"我_02"] forState:UIControlStateNormal];
//        [btnMore setBackgroundImage:[UIImage imageNamed:@"更多_01"] forState:UIControlStateNormal];
//        
//        labelHome.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        labelFind.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        labelMe.textColor = [UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1];
//        labelMore.textColor = [UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1];
//    }
//}
//
//-(IBAction)segmentAction:(UISegmentedControl *)Seg{
//    NSInteger Index = Seg.selectedSegmentIndex;
//    NSLog(@"Index %i", Index);
//    switch (Index) {
//        case 0:
//            findVC.view.hidden = NO;
//            findRecomVC.view.hidden = YES;
//            break;
//        case 1:
//            findVC.view.hidden = YES;
//            findRecomVC.view.hidden = NO;
//            break;
//        default:
//            break;
//    }
//}

- (void)btnActivityClicked:(id)sender {
    UIButton *btn = (UIButton *)sender;
    NSDictionary *dicActivity = [mutableArrayActivity objectAtIndex:btn.tag];
    
    WebViewController *vc = [[WebViewController alloc] init];
    vc.url = [dicActivity valueForKeyPath:@"html"];
    vc.vcTitle = [dicActivity valueForKeyPath:@"title"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)createCard {
    CGFloat width = CGRectGetWidth(self.scrollViewActvity.frame)/4 - 5;
    CGFloat height = CGRectGetHeight(self.scrollViewActvity.frame);
    
    for (int i = 0; i < [mutableArrayActivity count]; i++) {
        NSDictionary *dicActivity = [mutableArrayActivity objectAtIndex:i];
        CGFloat x = self.scrollViewActvity.subviews.count * width + (self.scrollViewActvity.subviews.count + 1)*4;
        
        UIButton *btnActivity = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, width, height)];
        btnActivity.layer.cornerRadius = 8.;
        
        NSString *imagePath = [NSString stringWithFormat:@"%@/%@", IMAGE_URL, [dicActivity valueForKeyPath:@"album_thumb"]];
        [btnActivity sd_setImageWithURL:[NSURL URLWithString:imagePath] forState:UIControlStateNormal];
        [btnActivity addTarget:self action:@selector(btnActivityClicked:) forControlEvents:UIControlEventTouchUpInside];
        btnActivity.tag = i;
        [self.scrollViewActvity addSubview:btnActivity];
        self.scrollViewActvity.contentSize = CGSizeMake(x + width, height);
    }
}

- (void) getActivityData {
    //读取本地数据库是否有该文件
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           self.parkId, @"parkid",
                           @"20", @"limit",nil];
    
    [service getNetWorkData:param
                       Path:PARK_ACTIVITY
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"rows"];
                      
                      for (NSDictionary* attributes in array) {
                          [mutableArrayActivity addObject:attributes];
                      }
                      
                      [self createCard];
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                  }];
}

- (BOOL) loadSpotData {
//    // 调整示例frame
//    NSString *fileName = @"getSource";//[NSString stringWithFormat:@"park_%@.zip",parkEntity.ID ];
//    //NSString *aSavePath = @"lyss";
//    
//    //检查本地文件是否已存在
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//    NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
//    NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",parkEntity.ID ];
//    NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
//    NSString *filePath = [park_path stringByAppendingPathComponent:fileName];
//    
//    if (![fileManager fileExistsAtPath:folder]) {
//        BOOL blCreateFolder= [fileManager createDirectoryAtPath:folder withIntermediateDirectories:NO attributes:nil error:NULL];
//        if (blCreateFolder) {
//            blCreateFolder= [fileManager createDirectoryAtPath:park_path withIntermediateDirectories:NO attributes:nil error:NULL];
//            if (blCreateFolder) {
//                NSLog(@" folder success2");
//            }else {
//                NSLog(@" folder fial2");
//            }
//        }
//        if (blCreateFolder) {
//            NSLog(@" folder success");
//        }else {
//            NSLog(@" folder fial");
//        }
//    } else {
//        NSLog(@" 沙盒文件已经存在");
//    }
//    
//    if ([DBManager selectParkByParkId:parkEntity.ID] != nil) {// && [fileManager fileExistsAtPath:filePath]
//        
//        CommonService *service = [[CommonService alloc] init];
//        
//        if ([arraySpot count] == 0) {
//            if ([service getSpotDataFromLocal:self.parkId
//                                    ArraySpot:arraySpot
//                                ArrayBusiness:arrayBusiness
//                                  ArrayToilet:arrayToilet
//                                ArrayRoadLine:arrayRoadLine
//                                   ParkEntity:parkEntity] == YES) {
//                return YES;
//            } else {
//                ALERT_ERR_MSG(@"加载本地资源失败");
//                return NO;
//            }
//        } else {
//            return YES;
//        }
//    } else {
//        DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"提示"
//                                                    contentText:@"下载景区资料？"
//                                                leftButtonTitle:@"取消"
//                                               rightButtonTitle:@"确定"];
//        [alert show];
//        alert.leftBlock = ^() {
//            NSLog(@"left button clicked");
//        };
//        alert.rightBlock = ^() {
//            [self downloadPackage];
//        };
//        alert.dismissBlock = ^() {
//            NSLog(@"Do something interesting after dismiss block");
//        };
        return NO;
//    }
//    
}

- (void) downloadPackage {
    
    UserEntity *user = [UserEntity sharedInstance];
    LocationManagement *lm = [LocationManagement sharedInstance];
    NSString *longitude = [NSString stringWithFormat:@"%f", lm.location.coordinate.longitude ];
    NSString *latitude = [NSString stringWithFormat:@"%f", lm.location.coordinate.latitude ];
    
    NSString *url = [NSString stringWithFormat:@"%@%@?parkid=%@&userid=%@&longitude=%@&latitude=%@&phone_guid=%@",
                     BASEURL, PARK_SOURCE, parkEntity.ID, user.userId, longitude, latitude, [OpenUDID value] ];
    NSString *fileName = [NSString stringWithFormat:@"park-%@.zip",parkEntity.ID ];
    //NSString *aSavePath = @"lyss";
    
    //检查本地文件是否已存在
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
    NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
    NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",parkEntity.ID ];
    NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
    
    NSString *filePath = [park_path stringByAppendingPathComponent:fileName];
    
    if (![fileManager fileExistsAtPath:folder]) {
        BOOL blCreateFolder= [fileManager createDirectoryAtPath:folder withIntermediateDirectories:NO attributes:nil error:NULL];
        if (blCreateFolder) {
            blCreateFolder= [fileManager createDirectoryAtPath:park_path withIntermediateDirectories:NO attributes:nil error:NULL];
            if (blCreateFolder) {
                NSLog(@" folder success2");
            }else {
                NSLog(@" folder fial2");
            }
        } else {
            
        }
        if (blCreateFolder) {
            NSLog(@" folder success");
        }else {
            NSLog(@" folder fial");
        }
    } else {
        NSLog(@" 沙盒文件已经存在");
    }
    
    //NSString* path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/lysss"];
    if (![fileManager fileExistsAtPath:filePath]) {
        progressView.hidden = NO;
        _downloading = YES;
        [progressView setProgress:0];
        _labelProgress.hidden = NO;
        //判断是否链接LET-FI设备，并试图读取SD卡上的相关内容
        NSString *LET_FI_URL = [NSString stringWithFormat:@"%@/resource/park-%@.zip", LET_FI, parkEntity.ID];
        [self downloadPackage:LET_FI_URL ParkPath:park_path];
//        if ([CommonService isExistenceLETFINetwork:LET_FI_URL] == YES) {
//            [self downloadPackage:LET_FI_URL ParkPath:park_path];
//        } else {
//            [self downloadPackage:url ParkPath:park_path];
//        }
    } else {
        NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:filePath];
        NSData *data = [file readDataToEndOfFile];//得到xml文件
        
        NSString* aStr;
        aStr = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];         //转换为NSString
        NSLog( @"aStr is %@", aStr );
    }
}

- (void)cancelAll:(id)sender
{
    [self.sharedDownloadManager cancelAllDownloadsAndRemoveFiles:YES];
}


#pragma mark - BlobDownloadManager Delegate (Optional, your choice)


- (void)download:(TCBlobDownload *)blobDownload didReceiveFirstResponse:(NSURLResponse *)response {
}

- (void)download:(TCBlobDownload *)blobDownload
  didReceiveData:(uint64_t)receivedLength
         onTotal:(uint64_t)totalLength {
    
}

- (void)download:(TCBlobDownload *)blobDownload didStopWithError:(NSError *)error {
}

- (void)download:(TCBlobDownload *)blobDownload didCancelRemovingFile:(BOOL)fileRemoved {
    
}

- (void)downloadDidFinishWithDownload:(TCBlobDownload *)blobDownload {
    
}

- (void) handleNotification:(NSDictionary *)alertInfo {
//    [self showMainView:2];
    self.tabBarController.selectedIndex = 2;
    dicPushMessage = alertInfo;
    
    NSDictionary *aps = [alertInfo valueForKeyPath:@"aps"];
    NSString *message = [aps valueForKeyPath:@"alert"];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"推送消息"
                                                    message:message
                                                   delegate:self
                                          cancelButtonTitle:@"忽略"
                                          otherButtonTitles:@"消息查看", nil];
    alert.tag = 11000;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag == 11000) {
        if (buttonIndex == 1) {
            WebViewController *vc = [[WebViewController alloc] init];
            vc.url = [dicPushMessage valueForKeyPath:@"url"];
            vc.vcTitle = [dicPushMessage valueForKeyPath:@"title"];
            vc.imageShare = [UIImage imageNamed:@"icon"];
            [self.navigationController pushViewController:vc animated:YES];
        }
    } else if (alertView.tag == 90000) {
        if (buttonIndex == 1) {
            NSURL *url = [NSURL URLWithString:super.appURL];
            [[UIApplication sharedApplication]openURL:url];
        }
    }
}

- (BOOL) downloadPackage:(NSString *)url ParkPath:(NSString *)park_path{
    return [self.sharedDownloadManager startDownloadWithURL:[NSURL URLWithString:url]
                                          customPath:park_path
                                       firstResponse:^(NSURLResponse *response) {
                                       }
                                            progress:^(float receivedLength, float totalLength) {
                                                NSLog(@"totalBytesRead = %f totalBytesExpectedToRead = %f",receivedLength,totalLength);
                                                float progress = receivedLength / (float)totalLength;
                                                [progressView setProgress:progress];
                                                _labelProgress.text = [NSString stringWithFormat:@"(%.1f%%)", progress*100.0];
                                                
                                                parkEntity.package_size = [NSString stringWithFormat:@"%fM", totalLength/(1024.0*1024)];
                                            }
                                               error:^(NSError *error) {
                                                   progressView.hidden = YES;
                                                   _labelProgress.hidden = YES;
                                                   _downloading = NO;
                                                   NSLog(@"error = %@",error);
                                                   
                                                   if ([url containsString:LET_FI] == YES) {
                                                       UserEntity *user = [UserEntity sharedInstance];
                                                       LocationManagement *lm = [LocationManagement sharedInstance];
                                                       NSString *longitude = [NSString stringWithFormat:@"%f", lm.location.coordinate.longitude ];
                                                       NSString *latitude = [NSString stringWithFormat:@"%f", lm.location.coordinate.latitude ];
                                                       
                                                       NSString *url = [NSString stringWithFormat:@"%@%@?parkid=%@&userid=%@&longitude=%@&latitude=%@&phone_guid=%@",
                                                                        BASEURL, PARK_SOURCE, parkEntity.ID, user.userId, longitude, latitude, [OpenUDID value] ];
                                                       [self downloadPackage:url ParkPath:park_path];
                                                       progressView.hidden = NO;
                                                       _labelProgress.hidden = NO;
                                                       _downloading = YES;
                                                   } else {
                                                       ALERT_ERR_MSG(DownloadWebsiteSourceFail);
                                                   }
                                               }
                                            complete:^(BOOL downloadFinished, NSString *pathToFile) {
                                                progressView.hidden = YES;
                                                _labelProgress.hidden = YES;
                                                
                                                //定义一个布尔类型的对象
                                                BOOL ifsucess;
                                                //在objective－c种，正确是YES 错误是NO
                                                ifsucess = NO;
                                                //获取上面fileData对象中通过NSFileManager对象获取的文件中的内容，然后再创建一个新的路径，并存储
                                                
                                                //                                                    if (operation.responseData != nil) {
                                                //                                                        DebugLog(@"%@", @"operation.responseData not nil");
                                                //                                                    }
                                                //                                                    ifsucess = [fileManager createFileAtPath:filePath contents:operation.responseData attributes:nil];
                                                NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:pathToFile];
                                                NSData *data = [file readDataToEndOfFile];//得到xml文件
                                                //对布尔型对象进行判断
                                                if(data) {
                                                    NSLog(@"create file sucess");
                                                    //we need save this data to the sqlite
                                                    parkEntity.local_path = pathToFile;
                                                    
                                                    //解压压缩包
                                                    ZipArchive *za = [[ZipArchive alloc] init];
                                                    if ([za UnzipOpenFile: pathToFile]) {
                                                        BOOL ret = [za UnzipFileTo:park_path overWrite: YES];
                                                        if (NO == ret){
                                                            NSLog(@"za UnzipFileTo fail");
                                                            ALERT_ERR_MSG(@"解压失败");
                                                        } else {
                                                            ALERT_ERR_MSG(@"解压成功");
                                                            
                                                            //删除压缩包文件
                                                            [CommonService deleteFile:pathToFile];
                                                            //获取文件夹的大小
                                                            parkEntity.package_size = [CommonService getFolderSize:parkEntity.ID];
                                                            
                                                            [DBManager createTable];
                                                            [DBManager saveOrUpdataParkEntity:parkEntity];
                                                            
                                                            CommonService *service = [[CommonService alloc] init];
//                                                            if ([service getSpotDataFromLocal:self.parkId
//                                                                                    ArraySpot:arraySpot
//                                                                                ArrayBusiness:arrayBusiness
//                                                                                  ArrayToilet:arrayToilet
//                                                                                ArrayRoadLine:arrayRoadLine
//                                                                                   ParkEntity:parkEntity] == YES) {
//                                                                ALERT_ERR_MSG(@"景区资料下载完成");;
//                                                            } else {
//                                                                ALERT_ERR_MSG(@"加载本地资源失败");
//                                                            }
                                                        }
                                                        [za UnzipCloseFile];
                                                    } else {
                                                        
                                                    }
                                                } else {
                                                    if ([url containsString:LET_FI] != YES) {
                                                        ALERT_ERR_MSG(DownloadFail);
                                                    }
                                                }
                                                _downloading = NO;
                                            }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"MainViewController"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"MainViewController"];
}

@end


